let fs = require('fs')
let path = require('path');
let express = require('express')

let app = express();

app.use(express.static('./public'));
app.use(express.json());

app.get('/', (req, res) => {
    res.sendFile(fs.writeFileSync(path.join(__dirname, './public/index.html')))
})
app.get('/a', (req, res) => {
    res.sendFile(path.join(__dirname, './data.json'))
})
app.get('/book/index/:index', (req, res) => {
    let { index } = req.params;
    // 获取所有书籍
    let all = JSON.parse(fs.readFileSync('./data.json'))
    res.json(all[index]);
})
app.get('/likeBook/index/:index', (req, res) => {
    let { index } = req.params;
    // 获取所有书籍
    let all = JSON.parse(fs.readFileSync('./data.json'))
    let arr = JSON.parse(fs.readFileSync('./arr.json'))
    arr.push(all[index]);
    all[index].isLike = true;
    // 把数据写回文件
    fs.writeFileSync('./arr.json', JSON.stringify(arr))
    fs.writeFileSync('./data.json', JSON.stringify(all))

    res.json({
        code: 1,
        msg: "收藏成功"
    })
})
app.get('/no/book/:book', (req, res) => {
    let { book } = req.params;
    // 获取所有的小说
    let bookall = JSON.parse(fs.readFileSync('./arr.jsono8'));
    let index = book.indexOf(bookall)
    bookall.slice(index, 1)
    fs.writeFileSync('./arr.data', JSON.stringify(bookall))
    let arrbook = JSON.parse(fs.readFileSync('./arr.json'))
    arrbook.forEach((item) => {
        if (item.name === book) {
            item.isLike = false
        }
    })
    fs.writeFileSync('./data.json', JSON.stringify(arrbook))
    res.json({
        code: 3,
        msg: '取消收藏成功'
    })
})
app.listen(9000, () => {
    console.log('服务器启动成功http://localhost:9000')
})